package com.cloud.shopping.pay.mq;

import com.cloud.shopping.constants.RocketConstants;
import com.cloud.shopping.pay.service.WeChatPayService;
import com.cloud.shopping.tool.Signature;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author John.zhang
 * @version Id: RefundResultListener, v 1.0 2021/1/6 16:21 ZhiYong Exp $
 */
@Component
@RocketMQMessageListener(topic = RocketConstants.REFUND_TOPIC, consumerGroup = RocketConstants.CONSUMER_GROUP)
public class RefundResultListener implements RocketMQListener, RocketMQPushConsumerLifecycleListener {

    @Resource
    private Signature signature;

    @Resource
    private WeChatPayService weChatPayService;

    @Override
    public void onMessage(Object o) {

    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        defaultMQPushConsumer.registerMessageListener((MessageListenerConcurrently) (messages, context) -> {
            try {
                for (MessageExt msg : messages) {
                    //AES加密字符串
                    String result = new String(msg.getBody(), StandardCharsets.UTF_8);

                    //解密
                    Map<String, String> dataMap = signature.security(result);

                    //发送请求执行退款申请
                    Map<String, String> refundMap = weChatPayService.refund(dataMap);
                    System.out.println("退款申请状态---refundMap:"+refundMap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });
    }
}
